from rest_framework import serializers
from .models import Sku,skuAndAttribute,attribute
from buyHigh.settings.settings_dev import BASE_URL
class attributeSerializer(serializers.ModelSerializer):
    class Meta:
        model=attribute
        fields="__all__"
# 用于返回商品详情页的sku数据
class SkuSerializer(serializers.ModelSerializer):
    sku_name_arr=serializers.SerializerMethodField()
    goods_name=serializers.SerializerMethodField()
    goods_id=serializers.SerializerMethodField()
    _id=serializers.SerializerMethodField()
    image=serializers.SerializerMethodField()
    stock=serializers.SerializerMethodField()
    class Meta:
        model=Sku
        fields="__all__"
    def get_attribute(self,obj):
        sku_attribute_queryset=skuAndAttribute.objects.filter(sku=obj).values("attribute")
        attribute_queryset=attribute.objects.filter(id__in=sku_attribute_queryset)
        return attribute_queryset
    def get_sku_name_arr(self,obj):
        sku_name_arr=[]
        for attribute in self.get_attribute(obj):
            sku_name_arr.append(attribute.value)
        return sku_name_arr
    def get_goods_name(self,obj):
        return obj.product.name
    def get_goods_id(self,obj):
        return obj.product.id
    def get__id(self,obj):
        return obj.id
    def get_image(self,obj):
        print(obj.image.url)
        return BASE_URL+obj.image.url
    def get_stock(self,obj):
        return obj.stock-obj.frozen_stock
# 用于skuid查询出来的sku对象的序列化
class singleSkuSerializer(serializers.ModelSerializer):
    sku_name_arr=serializers.SerializerMethodField()
    goods_name=serializers.SerializerMethodField()
    cart_sku_num=serializers.SerializerMethodField()
    stock=serializers.SerializerMethodField()
    class Meta:
        model=Sku
        fields=["id","price","stock","sku_name_arr","goods_name","image",'cart_sku_num','freight','product',"original_price"]
    def get_sku_name_arr(self, instance):
        sku_name_arr=[]
        arttribute_queryset=skuAndAttribute.objects.filter(sku=instance)
        for SAobj in arttribute_queryset:
            sku_name_arr.append(SAobj.attribute.value)
        return sku_name_arr
    def get_goods_name(self, instance):
        return instance.product.name
    def get_cart_sku_num(self, instance):
        # 通过对象反向查询使用表名小写_set
        cartobj=instance.cartmodel_set.first()
        if not cartobj:
            return
        return cartobj.num
    def get_stock(self, instance):
        return instance.stock-instance.frozen_stock

